/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cw.server;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import cw.entity.Database;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author VinhTC
 */
public class DatabaseManagement {

    public DatabaseManagement() {
    }

    /**
     * getDatabaseParam
     * @return
     */
    public Database getDatabaseParam() {
        Database db = new Database();
        try {
            NodeList nodes = getNodeListOfPersistence();

            String url = "";
            String[] temp;
            String[] temp2;
            String[] temp3;
            for (int j = 0; j < nodes.getLength(); j++) {
                Element element = (Element) nodes.item(j);
                if (element.getAttribute("name").equals("javax.persistence.jdbc.url")) {
                    url = element.getAttribute("value").toString();
                    temp = url.split("=");
                    db.setDatabaseName(temp[1].toString());
                    temp2 = url.split("jdbc:sqlserver://");
                    temp3 = temp2[1].toString().split(";");
                    db.setServerName(temp3[0].toString());
                }
                if (element.getAttribute("name").equals("javax.persistence.jdbc.password")) {
                    db.setPassword(element.getAttribute("value").toString());
                }
                if (element.getAttribute("name").equals("javax.persistence.jdbc.user")) {
                    db.setUserName(element.getAttribute("value").toString());
                }
                if (element.getAttribute("name").equals("javax.persistence.jdbc.driver")) {
                    db.setDriver(element.getAttribute("value").toString());
                }
            }
            return db;
        } catch (Exception ex) {
            Logger.getLogger(DatabaseManagement.class.getName()).log(Level.SEVERE, null, ex);
            return db;
        }
    }

    /**
     * getNodeListOfPersistence
     * @return NodeList
     * @throws IOException
     * @throws ParserConfigurationException
     * @throws XPathExpressionException
     * @throws SAXException
     */
    public NodeList getNodeListOfPersistence() throws IOException, ParserConfigurationException, XPathExpressionException, SAXException {
        String expression = "//persistence/persistence-unit/properties/property";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        InputStream is = Thread.currentThread().getContextClassLoader().getResource("META-INF/persistence.xml").openStream();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        NodeList nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
        return nodes;
    }

    /**
     * configDatabase
     * @param db
     * @return
     */
    public boolean configDatabase(Database db) {
        boolean result = false;
        try {
            String expression = "//persistence/persistence-unit/properties/property";
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            InputStream is = Thread.currentThread().getContextClassLoader().getResource("META-INF/persistence.xml").openStream();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xpath = xpathFactory.newXPath();
            NodeList nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
            Element element;
            for (int j = 0; j < nodes.getLength(); j++) {
                element = (Element) nodes.item(j);
                if (element.getAttribute("name").equals("javax.persistence.jdbc.url")) {
                    StringBuilder url = new StringBuilder();
                    url.append("jdbc:sqlserver://");
                    url.append(db.getServerName());
                    url.append(";databaseName=");
                    url.append(db.getDatabaseName());
                    element.setAttribute("value", url.toString());
                }
                if (element.getAttribute("name").equals("javax.persistence.jdbc.password")) {
                    element.setAttribute("value", db.getPassword());
                }
                if (element.getAttribute("name").equals("javax.persistence.jdbc.user")) {
                    element.setAttribute("value", db.getUserName());
                }
            }

            String path = "";
            path = Thread.currentThread().getContextClassLoader().getResource("META-INF/persistence.xml").getPath();
            path = path.replace("%20", " ");
            path.substring(1, path.length());
            System.out.println("Path: " + path);

            FileOutputStream fos = new FileOutputStream(new File(path));
            outputData(doc, fos);
            fos.close();
            result = true;
        } catch (Exception ex) {
            Logger.getLogger(DatabaseManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     *
     * @param doc
     * @param output
     * @throws Exception
     */
    public void outputData(Document doc, OutputStream output) throws Exception {
        try {
            OutputFormat format = new OutputFormat();
            format.setIndenting(true);

            XMLSerializer xs = new XMLSerializer(output, format);

            xs.serialize(doc);

            output.flush();
        } catch (Exception e) {
            throw e;
        }
    }

    public static void main(String[] args) {
        DatabaseManagement dmng = new DatabaseManagement();
        Database db = new Database();

        db.setDatabaseName("Puzzle1");
        db.setServerName("localhost1");
        db.setUserName("sa1");
        db.setPassword("1111111");
        if (dmng.configDatabase(db)) {
            System.out.println("Success config db");
        }

        db = dmng.getDatabaseParam();

        System.out.println("driver: " + db.getDriver());
        System.out.println("username: " + db.getUserName());
        System.out.println("password: " + db.getPassword());
        System.out.println("dbName: " + db.getDatabaseName());
        System.out.println("serverName: " + db.getServerName());
//        int size = 2;
//        int[][] pos = new int[size][size];
//        for (int i = 0; i < 2; i++) {
//            for (int j= 0; j < 2; j++) {
//                pos[i][j] = i;
//            }
//        }
//
//        for (int i= 0; i < pos.length; i++) {
//            System.out.println("row: "+ pos[i]);
//        }
    }
}
